import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/my/order_list_entity.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/server/api_dir.dart';

enum PurchaseType {
  plan(name: "专家方案", api: "/${ApiDir.plan}/app-plan-do/orderList"),
  planForm(name: "计划单", api: "/${ApiDir.plan}/app-plan-list/orderList"),
  ai(name: "模型", api: "/${ApiDir.ai}/app-ai-order/orderList"),
  vip(name: "会员", api: "/${ApiDir.user}/app-user-vip/orderList"),
  secret(name: "海外情报", api: "/${ApiDir.info}/app-reveal/orderList"),
  subs(name: "专家订阅", api: "/${ApiDir.plan}/app-idea/orderList"),
  couponPack(
      name: "超值券包",
      api: "/${ApiDir.activity}/app-act-goods-group-do/couponPackageOrderList");

  final String name;
  final String api;

  const PurchaseType({required this.name, required this.api});
}

class MyPurchaseLogic extends GetxController with GetTickerProviderStateMixin {
  int pageSize = 15;
  int index = 0;
  List<String> tabs = PurchaseType.values.map((e) => e.name).toList();
  late List<int> pageIndex = List.generate(tabs.length, (index) => 1);
  late List<List<OrderListEntity>?> pageList =
      List.generate(tabs.length, (index) => []);
  EasyRefreshController refreshController =
      EasyRefreshController(controlFinishLoad: true);
  late TabController tabController =
      TabController(length: tabs.length, vsync: this);

  @override
  void onInit() {
    tabController.addListener(() {
      if (index != tabController.index) {
        index = tabController.index;
        getData();
        refreshController.resetFooter();
      }
    });
    super.onInit();
  }

  @override
  void onReady() {
    getData();
    super.onReady();
  }

  Future getData() async {
    final list = await PayApi.orderList(
        PurchaseType.values[index], pageIndex[index], 15);
    if (list != null) {
      pageList[index]?.addAll(list);
    }
    update();
  }

  void getRefresh() {
    pageIndex[index] = 1;
    pageList[index] = [];
    getData();
    refreshController.resetFooter();
    update();
  }

  void loadMore() {
    pageIndex[index] += 1;
    getData();
    refreshController.finishLoad(
        (pageList[index]?.length ?? 0) < pageIndex[index] * 15
            ? IndicatorResult.noMore
            : IndicatorResult.success);
    update();
  }
}
